<?php
namespace PsiFramework\Classes\Util\Parameters;

import("Classes.Model.ModelInterface.IPrimitiveObject");
import("Classes.Util.Object.Json");
import("Classes.Util.Object.ReferenceObject");
import("Classes.Util.Database.Query.SqlType");

use \PsiFramework\Classes\Util\Database\Query\SqlType;
use \PsiFramework\Classes\Model\ModelInterface\IPrimitiveObject;
use \PsiFramework\Classes\Util\Object\Json;
use \PsiFramework\Classes\Util\Object\ReferenceObject;

/**
 * PsiFramework
 * Php Simple Framework
 *
 * @author Rémi San
 * @version beta
 */

/**
 *
 *
 * @package Util.Parameters
 */
class JsonParameters implements IPrimitiveObject
{

    protected /*array*/ $_parameters ;

    public function __construct(/*array*/ $parameters=array())
    {
        $this->_parameters = $parameters ;
    }

    public function getParameters()
    {
        return $this->_parameters ;
    }

    public function setParameters(Json $parameters)
    {
        $this->_parameters = $parameters ;
    }

    public function get(/*string*/ $name)
    {
        if (array_key_exists($name, $this->_parameters)) {
            return $this->_parameters[$name] ;
        } else {
            return null ;
        }
    }

    public function set(/*string*/ $name, $value)
    {
        $this->_parameters[$name] = $value ;
    }

    public function serialize(/*bool*/ $asText=true)
    {
        $json = new \stdClass();
        foreach ($this->_parameters as $parameter=>$value) {
            $serializedValue = null ;
            if ($value instanceof IPrimitiveObject) {
                $serializedValue = $value->serialize(false);
            } else {
                $serializedValue = $value ;
            }

            $json->$parameter = $serializedValue ;
        }
        $jsonObject = new Json($json);

        return $jsonObject->serialize($asText);
    }

    public function unserialize(/*string*/ $text)
    {
        $jsonObject = new Json();
        $jsonObject->unserialize($text);

        foreach ($jsonObject->getObject() as $name=>$value) {
            $unserializedValue = null ;
            if (is_object($value)) {
                $unserializedValue = new ReferenceObject();
                $unserializedValue->unserialize($value);
            } else {
                $unserializedValue = $value ;
            }

            $this->set($name, $unserializedValue);
        }
    }

    public function toString()
    {

    }

    public static function getSqlType()
    {
        return SqlType::$text ;
    }
}
